import React, {Component} from 'react'
import {
    DeviceEventEmitter,
    Image,
    ListView,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from "react-native";
import CommonUtils from "../../common/CommonUtils";
import StyleUtils from "../../res/styles/StyleUtils";
import Navigation from "../../custom/Navigation";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../httpUtils/IparNetwork";
import Carousel from 'react-native-banner-carousel';
import GoodsRender from "../../utils/GoodsRender";
import I18n from "../../res/language/i18n";
import IparImageView from "../../custom/IparImageView";

export default class GoodsIsBuyPage extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        let ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 != row2,});
        this.commonUtils = new CommonUtils();
        this.state = {
            dataSource: ds,
            swap_amount: 0,
            currency_code: '',
            onLoadEndImg: false,
            showLoading: false,
            sliAdver: [],
        };
        this.iparNetWork = new IparNetwork();
    }

    componentWillUnmount() {
        this.iparNetWork = null;
        this.commonUtils = null;

    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('country_iso')
            .then((country) => {

                this.country = country
                CommonUtils.getAcyncInfo('userInfo')
                    .then((result) => {
                        let _param = JSON.parse(result).rank == 6 ? '&market=u2' : '';
                        this.onLOadData(country, _param);//获取首页数据
                    }).catch(() => {
                    this.onLOadData(country, '');//获取首页数据
                });
            });


        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                if (result) {
                    this.setState({
                        swap_amount: JSON.parse(result).swap_amount,
                        currency_code: JSON.parse(result).currency_code,
                    })
                }
            });


    }


    /**
     * 获取产品来表
     * @param country 哪个国家（CN/KZ....）
     * @param _param
     */
    onLOadData(country, _param) {
        let dataSource = this.props.goodsData;
        if (dataSource) {
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(dataSource.goods || []),
                sliAdver: dataSource.top || []
            });
            return;
        }

        this.setState({showLoading: true});

        let isBuyArr = [];
        let goodsPage = this.props.goodsPage;
        if (goodsPage === 'ibm') {
            this.iparNetWork.getRequest(SERVER_TYPE.goods + 'home?', 'country=' + country + _param)
                .then((result) => {
                    this.setState({showLoading: false});
                    if (result.code === 200) {
                        for (i = 0; i < result.data.goods.length; i++) {
                            for (j = 0; j < result.data.goods[i].goods.length; j++) {
                                if (result.data.goods[i].goods[j].is_buy === 1) {
                                    isBuyArr.push(result.data.goods[i].goods[j]);
                                }
                            }
                        }
                        this.setState({
                            dataSource: this.state.dataSource.cloneWithRows(isBuyArr),
                            sliAdver: result.data.sli_adver || []
                        })


                    }
                })
                .catch((error) => {
                    console.log('GoodsIsBuyPage-error: ' + error);
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    this.setState({showLoading: false});
                });
        } else {

            let _serverType = 'goodsType?';
            let _resultParam = 'type=' + goodsPage + '&country=' + country + _param;
            if (this.props.goods_id) {
                _serverType = 'countryGoods?';
                _resultParam = 'goods_id=' + this.props.goods_id + '&country=' + country;
            } else if (this.props.type === 'bv_list') {
                _serverType = 'product/bv_list?';
                _resultParam = 'country=' + country;
            }

            this.iparNetWork.getRequest(SERVER_TYPE.goods + _serverType, _resultParam)
                .then((result) => {
                    if (result.code === 200 && result.data) {
                        let data = result.data;
                        this.setState({
                            sliAdver: data.top ? data.top : [],
                            dataSource: this.state.dataSource.cloneWithRows(data.goods || data),
                            showLoading: false
                        });
                    } else {
                        this.setState({showLoading: false});
                    }
                })
                .catch((error) => {
                    console.log('GoodsIsBuyPage-error: ' + error);
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    this.setState({showLoading: false});
                });
        }
    }


    render() {


        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    title={this.props.title}
                    titleImage={this.props.title ? null : require('../../res/images/ic_ipar_logo.png')}
                />
                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.showLoading}
                            onRefresh={() => {
                            }}
                        />
                    }>
                    <View style={[StyleUtils.flex]}>

                        {/*{ViewUtils.getTitleView('Goods ', 'io')}*/}
                        {this.state.sliAdver && this.state.sliAdver.length > 0 &&
                        <View style={{height: 200}}>
                            <Carousel
                                autoplay={true}
                                autoplayTimeout={3000}
                                loop={true}
                                index={0}
                                showsPageIndicator={false}
                            >
                                {this.state.sliAdver.map((item) => {
                                    return <TouchableOpacity
                                        onPress={() => this.commonUtils.onClickAdvers(item, this, this.country)}
                                    >
                                        <IparImageView
                                            errorImage={require('../../res/images/ic_image_fail.png')}
                                            resizeMode={'cover'}
                                            width={'100%'}
                                            height={'100%'}
                                            url={item.adver_img}/>
                                    </TouchableOpacity>
                                })}
                            </Carousel>
                        </View>}

                        <ListView
                            dataSource={this.state.dataSource}
                            renderRow={this.renderRow.bind(this)}
                             style={styles.listView}
                            pageSize={1}
                            automaticallyAdjustContentInsets={false}
                            contentContainerStyle={styles.gridListStyle}
                        />

                    </View>
                </ScrollView>

            </View>
        )
    }


    // 返回cell
    renderRow(rowData, sectionID, rowID) {
        return (
            <GoodsRender
                countryImage={rowData.is_global === 1}
                navigator={this.props.navigator}
                dataSource={rowData}/>
        );

    }


}


const styles = StyleSheet.create({
    gridListStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },

    headerImages: {
        width: '100%',
        height: '100%',
        resizeMode: 'cover',
    },
});

